package com.mh.common.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.mh.common.core.exception.BaseException;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

//Excel导入导出工具类
public class ExcelUtils {

    //日志记录: import org.slf4j.Logger
    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelUtils.class);

    /**
     * 导出Excel方法
     * @param list        数据列表
     * @param pojoClass   实体类类型
     * @param fileName    导出的Excel名称
     * @param resp        响应前端时需要设置些参数
     * @param params      导出参数: 标题,Sheet名称,是否创建表头,表格类型等
     */
    public static void exportExcel(List<?> list,
                                   Class<?> pojoClass,
                                   String fileName,
                                   HttpServletResponse resp,
                                   ExportParams params) {
        Workbook sheets = ExcelExportUtil.exportExcel(params, pojoClass, list);
        //调用文件下载方法(自定义方法)
        downLoadExcel(fileName,resp,sheets);

    }

    private static void downLoadExcel(String fileName, HttpServletResponse resp, Workbook sheets) {

        ServletOutputStream os =null;

        try {
            //设置响应编码格式
            resp.setCharacterEncoding("UTF-8");
            //设置文件名和下载方式(详细说明在Web集成导出笔记中,代码EasyPOI_Boot模块的CourseController类)
            resp.setHeader("Content-Disposition","attachment;fileName="
                            + URLEncoder.encode(fileName,"UTF-8"));
                            //java.net.URLEncoder;

            //通过resp获取文件输出流
            os = resp.getOutputStream();
            //文件通过输出流写出去
            sheets.write(os);

        } catch (Exception e) {

            LOGGER.error("导出Excel异常:{}",e.getMessage());
            throw new BaseException("500","导出Excel失败,请联系系统管理员");

        } finally {
            try {
                //关闭流
                sheets.close();
                os.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
